var homePage = '/config/user';

//访问路径第一层
var firstPath = '/account/member';

var vLogin = new Vue({
    //对应div的id
    el: '#login',
    data: function () {
        return {
            loginType: 'account',
            loginError: '',
            phoneError: '', //错误提示信息
            imgSrc: METHOD_URL + firstPath + "/loginCode/getVerifyCode", //图形验证码
            registerHref: '/register',
            accountForm: {
                userName: 'admin', password: '123456', code: ''
            }, //账户表单属性
            accountRules: {
                userName: [{required: true, message: '账号不能为空', trigger: 'blur'}],
                password: [{required: true, message: '密码不能为空', trigger: 'blur'}],
                code: [{required: true, message: '验证码不能为空', trigger: 'blur'}]
            }, //账户表单验证规则
            phoneForm: {
                phone: '', smsCode: '', code: ''
            }, //手机表单属性
            phoneRules: {
                phone: [{validator: checkPhone, trigger: 'blur'}],
                smsCode: [{required: true, message: '短信验证码不能为空', trigger: 'blur'}],
                code: [{required: true, message: '图形验证码不能为空', trigger: 'blur'}]
            }, //手机表单验证规则
            sendFlag: false, //是否能够发送短信
            btnDisabled: false, //按钮不可用
            btnSendCode: '获取验证码', //验证码按钮
            InterValObj: '', //timer变量，控制时间
            count: 60, //间隔函数，1秒执行
            curCount: '' //当前剩余秒数
        }
    },
    mounted() {
        console.log(this.imgSrc);
    }
});

/**
 * 使用账号登录
 */
function loginByAccount() {
    vLogin.loginType = 'account';
    refreshAccountImg();
}

/**
 * 使用手机号码登录
 */
function loginByPhone() {
    vLogin.loginType = 'phone';
    refreshPhoneImg();
}

/**
 * 表单提交
 */
function loginSubmit() {
    console.log(vLogin.loginType);
    if (vLogin.loginType == 'account') {
        submitByAccount();
    }
    if (vLogin.loginType == 'phone') {
        submitByPhone();
    }
}

/**
 * 提交账号表单
 */
function submitByAccount() {
    vLogin.$refs.accountForm.validate(function (valid) {
        if (valid) {
            comparePicCode();//验证码
        }
    });
}

/**
 *  提交手机表单
 */
function submitByPhone() {
    vLogin.$refs.phoneForm.validate(function (valid) {
        if (valid) {
            comparePicCode(); //验证码
        }
    });
}

/**
 * 自定义检验手机号码格式
 */
function checkPhone(rule, value, callback) {
    let result = VERIFY_PHONE.test(value);
    if (!value) {
        return callback(new Error("请输入手机号码"));
    } else if (!result) { //手机格式不正确
        return callback(new Error("请输入正确手机号码"));
    } else {
        vLogin.sendFlag = true; //可以发送短信
        callback();
    }
}

/**
 * 图形验证码验证
 */
function comparePicCode() {
    //设置参数
    let data;
    if (vLogin.loginType == 'account') {
        data = {
            picCode: vLogin.accountForm.code
        }
    } else if (vLogin.loginType == 'phone') {
        data = {
            picCode: vLogin.phoneForm.code
        }
    }
    console.log(vLogin.loginType);
    console.log(data);
    //调用业务端方法
    let url = firstPath + "/loginCode/comparePicCode";
    CallAjaxPost(url, data, comparePicCodeSuc);
}

function comparePicCodeSuc(data) {
    console.log('图形验证码', vLogin.loginType, data);
    //1.验证码错误或后台异常直接返回
    if (data.obj === "fail") {
        //验证码错误,刷新页面，选择性重置相关值
        if (vLogin.loginType === 'phone') {
            vLogin.phoneError = '验证码错误，请重新输入！';
            vLogin.phoneForm.code = '';
            refreshPhoneImg();
            return;
        }
        if (vLogin.loginType === 'account') {
            vLogin.loginError = '验证码错误，请重新输入！';
            vLogin.accountForm.code = '';
            refreshAccountImg();
            return;
        }
    }
    // 2.验证码过期，重新生成验证码
    if (data.obj === 'codeExpired') {
        if (vLogin.loginType === 'phone') {
            vLogin.phoneError = '验证码已失效，请重新输入！';
            vLogin.phoneForm.code = '';
            refreshPhoneImg();
            return;
        }
        if (vLogin.loginType === 'account') {
            vLogin.loginError = '验证码已失效，请重新输入！';
            vLogin.accountForm.code = '';
            refreshAccountImg();
            return;
        }
    }
    // 3.验证码正确，验证用户名密码
    if (data.obj === 'success') {
        if (vLogin.loginType === 'account') {
            accountLogin();
        } else if (vLogin.loginType === 'phone') {
            phoneLogin();
        }
    }
}

/**
 * 验证用户名密码
 */
function accountLogin() {
    //设置参数
    let data = {
        account: vLogin.accountForm.userName,
        password: vLogin.accountForm.password
    };
    console.log(data);
    //调用业务端方法
    let url = firstPath + "/accountLogin";
    // CallAjaxPost(url, data, loginSuc);
    // 后台为spring security接收，用form表单的方式提交
    CallAjaxPostForm(url, data, loginSuc);
}

function loginSuc(data) {
    console.log(data);
    //1,验证码用户名密码错误
    if (data.obj === "fail") {
        vLogin.loginError = '用户名或密码错误！';
        resetParams();
        return;
    }
    if (data.obj.message === "success") {
        // 将用户信息放入cookie中
        window.cookieUtil.del("userName");
        window.cookieUtil.set("userName", data.obj.userName);
        // 将token放入cookie中
        window.cookieUtil.del("Authorization");
        window.cookieUtil.set("Authorization", data.obj.token);

        // 获取url中的参数
        let url = decodeURIComponent(GetUrlParam("redirectURL"));
        // 是否从别的页面跳转至登录页面
        if (IsNotEmpty(url)) {
            window.location.href = url;
        } else {
            window.location.href = homePage;
        }
    }
}

/**
 * 手机登录
 */
function phoneLogin() {
    //设置参数
    let data = {
        phone: vLogin.phoneForm.phone,
        smsCode: vLogin.phoneForm.smsCode
    };
    //调用业务端方法
    let url = firstPath + "/phoneLogin";
    CallAjaxPostForm(url, data, phoneLoginSuc);
}

function phoneLoginSuc(data) {
    console.log(data);
    switch (data.obj) {
        case "phoneError":
            vLogin.phoneErr = '手机号码有误！';
            resetParams();
            break;
        case "codeExpired":
            vLogin.phoneErr = '短信验证码失效！';
            resetParams();
            break;
        case "smsCodeErr":
            vLogin.phoneErr = '短信验证码有误！';
            resetParams();
            break;
        default:
            break;
    }
    if (data.obj.message === "success") {
        // 将用户信息放入cookie中
        window.cookieUtil.del("userName");
        window.cookieUtil.set("userName", data.obj.userName);
        // 将token放入cookie中
        window.cookieUtil.del("Authorization");
        window.cookieUtil.set("Authorization", data.obj.token);

        // 获取url中的参数
        let url = decodeURIComponent(GetUrlParam("redirectURL"));
        // 是否从别的页面跳转至登录页面
        if (IsNotEmpty(url)) {
            window.location.href = url;
        } else {
            window.location.href = homePage;
        }
    }
}


/**
 * 登录失败，重置相关参数并刷新验证码
 */
function resetParams() {
    vLogin.accountForm.password = '';
    vLogin.accountForm.code = '';
    vLogin.phoneForm.smsCode = '';
    vLogin.phoneForm.code = '';
    refreshAccountImg();
}

/**
 * 发送短信获取验证码
 */
function sendMessage() {
    if (vLogin.sendFlag) {
        //设置当前剩余秒数
        curCount = vLogin.count;
        InterValObj = setInterval(SetRemainTime, 1000); //启动计时器，1秒执行一次
        let data = {
            phone: vLogin.phoneForm.phone
        };
        //调动业务端方法
        let url = firstPath + "/loginPhone/sendMessage";
        CallAjaxPost(url, data, sendMessageSus);
    } else {
        //**********还没写好
        vLogin.phoneError = "请输入手机号码";
    }
}

/**
 * 需要封装成一个方法 switch/case
 * @param data
 */
function sendMessageSus(data) {
    //发送
    if (data.obj === 1016) {
        vLogin.loginError = '手机号格式错误';
        return;
    }
    if (data.obj === 1023) {
        vLogin.loginError = '30秒内下发短信条数超过上限';
        return;
    }
    if (data.obj === 1024) {
        vLogin.loginError = '1小时内下发短信条数超过上限';
        return;
    }
    if (data.obj === 1025) {
        vLogin.loginError = '今日发短信条数超过上限';
        return;
    }
    if (data.obj === 1031) {
        vLogin.loginError = '短信发送功能失效，请稍后再试';
        return;
    }
    if (data.obj === 0) {
        console.log("发送成功！")
    }
}

/**
 * timer处理函数
 * @constructor
 */
function SetRemainTime() {
    if (curCount === 0) {
        window.clearInterval(InterValObj); //停止计时器
        vLogin.btnDisabled = false; //短信按钮可用
        vLogin.btnSendCode = "重新获取";
    } else {
        vLogin.btnDisabled = true; //短信按钮不可用
        vLogin.btnSendCode = curCount + "秒后重发";
        curCount--; //当前秒数-1
    }
}

/**
 * 刷新账号验证码
 */
function refreshAccountImg() {
    let url = METHOD_URL + firstPath + "/loginCode/getVerifyCode?number=" + Math.random();
    $("#accountImg").attr("src", url);
}

/**
 * 刷新手机验证码
 */
function refreshPhoneImg() {
    let url = METHOD_URL + firstPath + "/loginCode/getVerifyCode?number=" + Math.random();
    $("#phoneImg").attr("src", url);
}

/**
 * 打开忘记密码页面
 */
function openForgetPwd() {
    let url = "/reset_password";
    window.open(url);
}


// 获取文件名
function getHeadersFName(conDspAttrs) {
    let fileName = '';
    conDspAttrs.forEach((item, index) => {
            let temp = item.split('=');
            if (temp.length > 1 && temp[0] === 'filename') {
                fileName = temp
            }
        }
    );
    return fileName;
}

function exportExcel() {
    let url = "/pos/exportPosTransStatistic";
    let data = {
        "caseId": 2,
    };

    // 二进制流解析下载
    // const fileName = this.getHeadersFName(res.headers['content-disposition'].split(';'));
    // console.log('文件名称：', fileName)
    // const blob = new Blob([res.data]);
    // const a = document.createElement('a');
    // const bUrl = window.URL.createObject
    // URL(blob);
    // a.download = fileName;
    // a.href = bUrl;
    // document.body.appendChild(a);
    // a.click()
    // document.body.removechild(a);

    let xhr = new XMLHttpRequest();
    // xhr.open('GET', 'http://127.0.0.1:8012/pos/exportPosTransStatistic?caseId=2', true);
    xhr.open('GET', 'http://192.168.3.110:8012/pos/exportPosTransStatistic?caseId=2', true);
    // xhr.open('GET', 'http://127.0.0.1:8012/pos/exportPosTransStatistic', true);
    xhr.responseType = "blob";
    xhr.setRequestHeader("client_type", "DESKTOP_WEB");

    // xhr.onreadystatechange = () => {
    xhr.onload = () => {
        console.log(xhr.status);
        if (xhr.readyState === 4 && xhr.status === 200) {
            console.log(xhr.getAllResponseHeaders());
            let headerfileName = xhr.getResponseHeader("Content-Disposition");
            if (headerfileName) {
                fileName = decodeURI(headerfileName.replace('attachment;filename=', ''));
            }
            // let blob = new Blob([xhr.response], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"});
            let blob = new Blob([xhr.response], {type: xhr.getResponseHeader("content-type")});
            let csvUrl = URL.createObjectURL(blob);
            let link = document.createElement('a');
            link.href = csvUrl;
            link.download = fileName;
            link.click();
        } else if (xhr.readyState === 4 && xhr.status === 420) {
            // TODO xhr.response是blob类型，需要转为JSON
            console.log('数据参数异常');
        } else if (xhr.readyState === 4 && xhr.status === 500) {
            console.log('下载服务异常');
        }
    }
    xhr.send();


    // xhr.onload = function () {
    //     console.log(this.response)
    //     if (this.status == 200) {
    //         debugger
    //         var blob = this.response;
    //         // const fileName = this.getHeadersFName(this.response.headers['content-disposition'].split(';'));
    //         // console.log('文件名称：', fileName)
    //         console.log('文件名称：', this.response.headers)
    //         //这里导出src
    //         var src = URL.createObjectURL(blob);
    //         var link = document.createElement('a');
    //         //设置下载的文件名
    //         link.download = fileName;
    //         link.style.display = 'none';
    //         //设置下载路径
    //         link.href = src;
    //         //触发点击
    //         document.body.appendChild(link);
    //         link.click();
    //         //移除节点
    //         document.body.removeChild(link);
    //     }
    // }
    // xhr.send();

    // $.ajax({
    //     url: 'http://127.0.0.1:8012' + url,
    //     async: true,
    //     xhrFields: {
    //         withCredentials: true
    //     },
    //     timeout: 20000,
    //     crossDomain: true,
    //     method: "get",
    //     data: data,
    //     contentType: "application/json; charset=utf-8",// 参数格式
    //     // dataType: "blob",
    //     // dataType: "json",
    //     success: function (data, textStatus) {
    //         debugger
    //         console.log("================");
    //         console.log(data, textStatus);
    //     },
    //     error: function (XMLHttpRequest, textStatus, errorThrown) {
    //         console.log(XMLHttpRequest, textStatus, errorThrown);
    //     },
    //     complete: function (XMLHttpRequest, textStatus) {
    //         console.log(XMLHttpRequest, textStatus);
    //     }
    // })
}